<template>
  <z-popup v-model="showPopup" duration="0" :style="popupStyle" @open="onOpen">
    <page-wrap :header-props="headerProps">
      <template #extension>
        <z-search
          v-model="searchVal"
          placeholder="请输入桌台号"
          @update:model-value="onUpdate"
        />
      </template>
      <div class="bookCheck-container">
        <z-sidebar
          :current-active="menuActive"
          :menu-list="zoneList"
          @click="onZone"
        />
        <div class="cm-table-simple">
          <z-empty type="data" v-if="!tableList.length" />
          <ul class="cm-table-simple-list" v-else>
            <li
              class="cm-table-simple-item"
              v-for="(item, index) in tableList"
              :key="index"
              @click="onCheck(item)"
            >
              <template v-if="line == 1">
                <div class="cm-table-simple__center">{{ item.roomName }}</div>
              </template>
              <template v-if="line == 2">
                <div class="cm-table-simple__title">{{ item.roomName }}</div>
                <div :class="getStateList(item.consumeState)">
                  {{ item.ConsumeStateName }}
                </div>
              </template>
            </li>
          </ul>
        </div>
      </div>
    </page-wrap>

    <!-- 并台 -->
    <z-popup v-model:show="showMergeTable" title="提示">
      <div class="mergeTable">
        <div class="mergeTable-tip" v-if="tableTitle === '并台'">
          是否确认并台?
        </div>
        <div class="mergeTable-tip" v-if="tableTitle !== '并台'">
          是否确认转台?
        </div>
        <div class="mergeTable-table">
          <div class="mergeTable-table-now">
            <span class="mergeTable-span-title">当前桌台：</span
            ><span class="mergeTable-span-value">{{ oldRoomName }}</span>
          </div>
          <div class="mergeTable-table-target">
            <span class="mergeTable-span-title">目标桌台：</span
            ><span class="mergeTable-span-value">{{ newRoomName }}</span>
          </div>
        </div>
        <div class="mergeTable-input" v-if="tableTitle === '并台'">
          <div class="mergeTable-input-title">并台人数</div>
          <van-field
            v-model="postForm.peopleCount"
            placeholder="请输入人数"
            class="mergeTable-input-value"
            type="digit"
          />
        </div>
        <!-- <van-radio-group
          v-model="postForm.isMergeConsume"
          direction="horizontal"
          class="mergeTable-select"
          shape="dot"
          v-if="tableTitle === '并台'"
        >
          <van-radio
            name="1"
            style="margin-right: 16px"
            class="mergeTable-select-item"
            checked-color="#FFAA00"
            >并账</van-radio
          >
          <van-radio
            name="2"
            class="mergeTable-select-item"
            checked-color="#FFAA00"
            >不并账</van-radio
          >
        </van-radio-group> -->
        <div class="mergeTable-button">
          <button
            class="mergeTable-button-cancle"
            @click="showMergeTable = false"
          >
            取消
          </button>
          <button class="mergeTable-button-confirm" @click="onConfirm">
            确认
          </button>
        </div>
      </div>
    </z-popup>
  </z-popup>
</template>
<script setup>
import { transformArrayProps } from '@/lib/util.js'
import useConfigStore from '@/store/config'
import Api from '@/api'
import { showToast } from 'vant'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  source: {
    type: String,
    required: true
  },
  line: {
    type: String,
    default: '2'
  },
  state: {
    type: [Number, String],
    default: '0' //0空闲，1预订，2使用，3未支付
  },
  tableCode: {
    type: [Number, String]
  },
  tableName: {
    type: String
  },
  tableConsumeCode: {
    type: [Number, String]
  },
  reserveCode: {
    type: [Number, String]
  },
  currentPeople: {
    type: [Number, String]
  }
})

const configStore = useConfigStore()
const router = useRouter()
const zoneActive = ref(0)
const menuActive = ref(0)
const zoneList = ref([])
const tableList = ref([])
const searchVal = ref('')
const showPopup = ref(true)
const emits = defineEmits(['close'])
const popupStyle =
  'margin:0;max-width:100%;width:100%;height:100%;overflow:hidden;'
const allTableList = ref([])
const tableState = toRef(props, 'state')
const source = props.source
const showMergeTable = ref(false) // 并台弹窗
const showTurnTable = ref(false) // 转台弹窗
const oldRoomName = ref('') // 旧桌台名
const newRoomName = ref('') // 新桌台名
const tableTitle = toRef(props, 'title') // 标题名
const currentPeople = ref('') // 点击并台时的人数
//表单
const postForm = reactive({
  peopleCount: '',
  oldRoomCode: '',
  newRoomCode: '',
  oldConsumeCode: '',
  newConsumeCode: '',
  reserveCode: ''
  // isMergeConsume: '1'
})
// 头部配置
const headerProps = computed(() => {
  let title = unref(tableTitle)
  if (unref(tableTitle) == '并台') {
    title = '并台'
  }
  if (unref(tableTitle) == '转台') {
    title = '转台'
  }
  if (unref(tableTitle) == '入座') {
    title = '入座'
  }
  const r = {
    title,
    backFn: () => {
      emits('close', 'back')
      showPopup.value = false
    }
  }
  return r
})

// 策略模式
const stateList = {
  0: '空闲',
  1: '预订',
  2: '使用',
  3: '未支付'
}

// 房台状态class
const getStateList = state => {
  return {
    'cm-table-simple__type': true,
    free: state == 0,
    book: state == 1,
    use: state == 2,
    nopay: state == 3
  }
}

// 监听sidebar切换
watch(zoneActive, nVal => {
  const list = unref(allTableList)
  if (nVal == '0') {
    tableList.value = list
  } else {
    tableList.value = list.filter(
      item =>
        item.roomAreaCode == nVal && item.roomAreaCode == unref(zoneActive)
    )
  }
  searchVal.value = ''
})

// 监听输入框值
const onUpdate = nVal => {
  const list = unref(allTableList)
  const regex = new RegExp(nVal, 'i')
  if (unref(zoneActive) == '0') {
    tableList.value = list.filter(item => regex.test(item.roomName))
  } else {
    tableList.value = list.filter(
      item =>
        regex.test(item.roomName) && item.roomAreaCode == unref(zoneActive)
    )
  }
}

const onZone = (code, k) => {
  zoneActive.value = code
  menuActive.value = k
}

// 选择桌台
const onCheck = item => {
  postForm.peopleCount = ''
  if (postForm.oldRoomCode === item.roomCode) {
    showToast('不可选同一桌号')
    return
  }
  newRoomName.value = item.roomName
  postForm.newConsumeCode = item.consumeCode
  postForm.newRoomCode = item.roomCode
  // console.log(props.title)
  if (props.title === '并台') {
    postForm.peopleCount = currentPeople.value
    showMergeTable.value = true
    return
  }
  if (props.title === '转台') {
    showMergeTable.value = true
    return
  }
  if (props.title === '入座') {
    // console.log(item);
    const openData = {
      // 预订页
      roomCode: item.roomCode,
      roomName: item.roomName,
      typeCode: item.typeCode,
      typeName: item.typeName,
      minConsume: item.minConsume,
      // 开台页
      reserveCode: '',
      // 常量
      consumeState: item.consumeState,
      source: 'open'
    }
    router.push({
      path: '/open/confirm',
      query: {
        from: 'queue',
        ...openData
      }
    })
    return
  }

  const { roomName, roomCode, typeCode, typeName, minConsume, consumeCode } =
    item
  const args = {
    roomName,
    roomCode,
    typeCode,
    typeName,
    minConsume,
    consumeCode
  }
  emits('close', 'check', args)
  showPopup.value = false
}
// 接收传过来的值
watch(
  () => props,
  newValue => {
    postForm.oldRoomCode = newValue.tableCode
    oldRoomName.value = newValue.tableName
    postForm.oldConsumeCode = newValue.tableConsumeCode
    postForm.reserveCode = newValue.reserveCode
    currentPeople.value = newValue.currentPeople
  },
  { deep: true }
)

// 确认
const onConfirm = () => {
  switch (tableTitle.value) {
    case '并台':
      if (!postForm.peopleCount) {
        showToast('请输入人数')
        return
      }
      // console.log(postForm)
      Api.Common.AppObjProcess.Do({
        functionName: 'RoomMerge',
        contentData: postForm
      }).then(res => {
        showToast('并台成功')
        showMergeTable.value = false
        emits('close', 'success')
        showPopup.value = false
      })
      break

    case '转台':
      // console.log(postForm)
      postForm.consumeCode = postForm.oldConsumeCode
      Api.Common.AppObjProcess.Do({
        functionName: 'RoomChange',
        contentData: postForm
      }).then(res => {
        showToast('转台成功')
        showMergeTable.value = false
        emits('close', 'success')
        showPopup.value = false
      })
      break
  }
}
// 初始化
const onInit = async function () {
  const trans = [
    ['roomAreaName', 'name'],
    ['roomAreaCode', 'code']
  ]
  zoneList.value = transformArrayProps(configStore.zoneList, trans)
  zoneList.value.unshift({ name: '全部', code: '0' })
  const resp = await Api.Common.AppObjProcess.Do({
    functionName: 'getRoomInfoNew',
    contentData: ''
  })
  let freeList = resp.result.filter(
    v => v.consumeState == '2' || v.consumeState == '3'
  )
  if (props.title === '并台') {
    freeList = freeList.filter(v => v.roomCode !== postForm.oldRoomCode)
  }
  // console.log(freeList)
  tableList.value = freeList
  allTableList.value = freeList

  // console.log(unref(allTableList))
}
// onInit()
const onOpen = () => {
  onInit()
}
</script>
<style scoped lang="scss">
.bookCheck-container {
  display: flex;
  padding-top: 10px;
  height: 100%;
  overflow: hidden;
}
.mergeTable {
  min-width: 300px;
  padding: 0 24px;
  .mergeTable-tip {
    text-align: center;
    padding: 20px 0 0 0;
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #cccccc;
    line-height: 16px;
  }
  .mergeTable-table {
    margin: 20px 0 9px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .mergeTable-table-now {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 14px;
      line-height: 14px;
      .mergeTable-span-title {
        color: #999999;
      }
      .mergeTable-span-value {
        color: #ffaa00;
      }
    }
    .mergeTable-table-target {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 14px;
      line-height: 14px;
      .mergeTable-span-title {
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 14px;
        line-height: 14px;
        color: #999999;
      }
      .mergeTable-span-value {
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 14px;
        line-height: 14px;
        color: #ffaa00;
      }
    }
  }
  .mergeTable-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    ::v-deep(.van-field__control) {
      color: #cccccc;
      font-size: 16px;
    }
    .mergeTable-input-title {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 16px;
      color: #cccccc;
      line-height: 16px;
    }
    .mergeTable-input-value {
      width: 180px;
      height: 40px;
      background: #5c5c66;
      border-radius: 4px;
    }
  }
  .mergeTable-select {
    display: flex;
    margin: 20px 0 0 0;
    ::v-deep(.van-radio__label) {
      color: #ffffff;
    }
    .mergeTable-select-item {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 16px;
      color: #ffffff;
      line-height: 16px;
    }
  }
  .mergeTable-button {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 30px 0 20px 0;
    .mergeTable-button-cancle {
      padding: 11px 42px;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #ccbea3;
      line-height: 18px;
      border-radius: 20px;
      background: #45454d;
      border: 1px solid #ccbea3;
    }
    .mergeTable-button-confirm {
      padding: 11px 42px;
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 18px;
      color: #260c04;
      line-height: 18px;
      background: linear-gradient(0deg, #cca67a, #fff4d9);
      border-radius: 20px;
    }
  }
}
</style>
